package com.example.blogsystem.config;

import com.example.blogsystem.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//定义一个拦截器
@Slf4j
@Configuration
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*
            1. 从header中获取token
            2.校验token
         */

        // 1) 获取token
        String userToken = request.getHeader( "user_token_header");//获取到报头中header
        if(userToken == null) {
            log.error("报头中的userToken为空");
        }
        log.info("userToken:{}", userToken);

        // 2) 校验token
        boolean checkToken = JwtUtil.verifyToken(userToken);
        if(checkToken) {
            //校验成功
            log.info("token校验成功");
            return true;
        }
        response.setStatus(401);
        log.error("token校验失败");
        return false;
    }
}
